package com.sumer.brain.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sumer.brain.common.constant.SystemConstant;
import com.sumer.brain.sys.mapper.SysUserMapper;
import com.sumer.brain.sys.model.entity.SysUser;
import com.sumer.brain.sys.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final PasswordEncoder passwordEncoder;

    private final SysUserMapper sysUserMapper;

    @Override
    public Boolean add(SysUser sysUser) {
        if (!StringUtils.hasText(sysUser.getPassword())) {
            sysUser.setPassword(SystemConstant.DEFAULT_PASSWORD);
        }
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        return save(sysUser);
    }

    @Override
    public SysUser getByUsername(String username) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, username);
        return getOne(lambdaQueryWrapper);
    }

    @Override
    public Boolean delByIds(String ids) {
        String[] idsArr = ids.split(",");
        return sysUserMapper.delByIds(idsArr) > 0;
    }
    
    @Override
    public SysUser findByWechatOpenId(String openId) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getWxOpenid, openId);
        return getOne(lambdaQueryWrapper);
    }
}